<template>
  <div class="app-container user">
    <van-nav-bar title="心理关爱师" left-arrow @click-left="$router.back()" />
    <div class="content">
      <div class="introduction-box">
        <div class="text">Hi~ 我是心理关爱师有什么可以帮您的！</div>
        <div class="tip">有心理上面的问题可以来这里哦~</div>
      </div>
      <div class="chat-box">
        <div class="msg-content">
          <el-scrollbar ref="scrollbarRef" style="height: 100%;">
            <div class="msg-row" :class="msg.role == 'user' && 'right'" v-for="(msg, index) in msgList" :key="index">
              <div class="user-info">
                <img class="avatar" :src="require(`@/assets/images/mindStation/${msg.role}_avatar.png`)" />
              </div>
              <div class="row-content" :class="msg.role">
                <div class="content-box" v-if="msg.content">
                  <template v-if="msg.content">
                    <!-- 文本 -->
                    <span class="text">{{ msg.content }}</span>
                    <!-- <div class="list-item-box" v-if="msg.scaleItem">
                    <div class="list-item">
                      <img class="item-cover"
                        :src="require(`@/assets/images/mindStation/scaleType${msg.scaleItem.scaleType}.png`)">
                      <div class="item-label-box">
                        <div class="item-label"><span class="tag">I-LEB</span>{{ msg.scaleItem.scaleName }}</div>
                        <div class="item-tip">{{ msg.scaleItem.description }}</div>
                      </div>
                    </div>
                    <div class="handel-box">
                      <div class="handle-btn"
                        @click="$router.push({ name: 'ExamTest', query: { scaleItem: JSON.stringify(msg.scaleItem), pageIndex: 'exam' } })">
                        {{ msg.scaleItem.recordCount ? '重新答题' : '开始答题' }}
                      </div>
                      <div class="handle-btn" v-if="msg.scaleItem.recordCount"
                        :class="msg.scaleItem.recordCount || 'disable'"
                        @click="$router.push({ name: 'ExamTest', query: { scaleItem: JSON.stringify(msg.scaleItem), pageIndex: 'result' } })">
                        查看报告
                      </div>
                    </div>
                  </div> -->
                  </template>
                  <i v-else class="el-icon-loading" />
                </div>
                <div class="follow-up-questions-list">
                  <i v-if="msg?.followUpQuestionsLoading" class="el-icon-loading" />
                  <template v-else>
                    <div class="follow-up-questions-item" v-for="item in  msg.followUpQuestions" :key="item"
                      @click="followUpQuestionsClick(item)">
                      {{ item }}
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <div class="question-box">
          <div class="asking-box">
            <div class="title">
              <span class="text">猜您想问</span>
              <i class="el-icon-arrow-down" v-if="showAskingList" @click="showAskingList = !showAskingList" />
              <i class="el-icon-arrow-right" v-else @click="showAskingList = !showAskingList" />
            </div>
            <div class="list-box" v-if="showAskingList">
              <div class="list-row" v-for="(row, index) in askingList" @click="askingListRowClick(row)">
                <span class="label">{{ `${index + 1}.${row.label}` }}</span>
                <i class="el-icon-arrow-right" />
              </div>
            </div>
          </div>
          <div class="input-box">
            <el-input placeholder="请输入你的内容" v-model="inputContent" @keyup.enter.native="sendQuestion">
              <i slot="suffix" v-if="dataLoading" class="el-icon-loading" />
              <svg-icon slot="suffix" v-else icon-class="send" @click="sendQuestion" />
            </el-input>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { generateUUID } from '@/utils/index.js';
import * as api from '@/api/mindStation/index.js';

export default {
  name: 'AiCustomerService',
  data() {
    return {
      dataLoading: false,
      isScrollOnBottom: true,
      msgList: [],
      inputContent: '',
      showAskingList: true,
      askingList: [
        { label: '我今天上班心情不好', botAnswer: true },
        { label: '我最近有点失眠', botAnswer: true },
        { label: '我最近感觉有点焦虑', botAnswer: true },
      ],
      sessionId: '',
    };
  },
  watch: {
    // 监听当前消息列表，更新时，保持滚动条位于底部
    msgList: {
      handler(val) {
        this.$nextTick(() => {
          // 判断是否滚动在底部
          if (this.isScrollOnBottom) {
            if (this.$refs.scrollbarRef) {
              const scrollbarRefWrap = this.$refs.scrollbarRef.$el.querySelector('.el-scrollbar__wrap');
              // this.$refs.scrollbarRef.wrap.scrollTop = scrollbarRefWrap.scrollHeight - scrollbarRefWrap.offsetHeight);
              this.$refs.scrollbarRef.wrap.scrollTop = scrollbarRefWrap.scrollHeight; // el-scrollbar滚动条
            }
          }
        });
      },
      deep: true,
    },
  },
  mounted() {
    this.handleScroll();
    this.sessionId = generateUUID();
  },
  methods: {
    // 处理滚动事件
    handleScroll() {
      this.$refs.scrollbarRef.wrap.onscroll = () => {
        if (this.$refs.scrollbarRef) {
          const scrollbarRefWrap = this.$refs.scrollbarRef.$el.querySelector('.el-scrollbar__wrap');
          const scrollTop = scrollbarRefWrap.scrollTop;
          const scrollHeight = scrollbarRefWrap.scrollHeight;
          const offsetHeight = scrollbarRefWrap.offsetHeight;
          // 用户开始滚动并在最底部之上，取消保持在最底部的效果
          if (scrollTop + offsetHeight + 5 < scrollHeight) this.isScrollOnBottom = false;
          // 用户停止滚动并滚动到最底部，开启保持到最底部的效果
          else this.isScrollOnBottom = true;
        }
      };
    },
    getData() {
      // this.dataLoading = true;
    },
    // 发送问题
    sendQuestion() {
      if (!this.inputContent) {
        this.$message.error('输入内容不能为空');
        throw Error;
      }
      if (!this.dataLoading) {
        this.msgList.push({ role: 'user', content: this.inputContent });
        this.botAnswer(this.inputContent);
        this.inputContent = '';
      }
    },
    // AI回答
    botAnswer(questionContent) {
      this.msgList.push({ role: 'robot', content: '', followUpQuestions: [], followUpQuestionsLoading: false });
      const msgItem = this.msgList[this.msgList.length - 1];
      // const url = 'http://10.18.124.22:8000/api/customerService-dialogue'; // SSE服务的URL
      // const url = 'http://183.56.241.175:6558/api/customerService-dialogue'; // SSE服务的URL
      const url = 'http://183.56.241.175:6558/soul/chat'; // SSE服务的URL
      let pre_chunk = ''; // 之前的值
      fetchEventSource(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        // body: JSON.stringify({ user_text: questionContent }),
        body: JSON.stringify({ user_input: questionContent, session_id: this.sessionId }),
        onopen(event) {
          console.log('建立连接', event);
        },
        onmessage: ({ data }) => {
          data = JSON.parse(data);
          // console.log('data', data);
          // if (data == '') data = '\n';
          if (data.chunk) {
            // console.log('data.chunk', data.chunk);
            // console.log('pre_chunk', pre_chunk);
            // console.log('data.chunk == ""  \n\n""', data.chunk == '  \n\n');
            // console.log('pre_chunk == ""  \n\n""', pre_chunk == '  \n\n');
            if (data.chunk == 'Answer') return (pre_chunk = data.chunk);
            if (data.chunk == ':' && pre_chunk == 'Answer') return;
            if (data.chunk == '  \n\n') {
              pre_chunk = data.chunk;
              msgItem.followUpQuestionsLoading = true;
              return;
            }
            if (pre_chunk == '  \n\n') return;
            pre_chunk = data.chunk;
            msgItem.content += data.chunk;
          }
          if (data.follow_up_questions) {
            msgItem.followUpQuestions = data.follow_up_questions;
          }
        },
        onclose: () => {
          console.log('连接关闭');
          msgItem.followUpQuestionsLoading = false;
        },
        onerror(event) {
          console.log('连接错误', event);
        },
      });
    },
    // followUpQuestions() {},
    // 机器人直接输出文本
    async botTyping(text) {
      this.msgList.push({ role: 'robot', content: '' });
      this.dataLoading = true;
      // setTimeout(() => {
      let msgItem = this.msgList[this.msgList.length - 1];
      this.dataLoading = false;
      await this.typing(msgItem, text);
      // }, 500);
    },
    // 打字效果输出
    typing(msgItem, text) {
      return new Promise((resolve) => {
        let charCount = 0;
        const timer = setInterval(() => {
          if (charCount < text.length) {
            msgItem.content += text.charAt(charCount);
            charCount++;
          } else {
            clearInterval(timer);
            resolve(); // 解析 Promise，表示完成
          }
        }, 30);
      });
    },
    // 关联问题点击
    followUpQuestionsClick(item) {
      this.msgList.push({ role: 'user', content: item });
      this.botAnswer(item);
    },
    // 猜你想问点击提问
    askingListRowClick(row) {
      if (row.botAnswer == true) {
        this.inputContent = row.label;
        this.sendQuestion();
      } else {
        api.getAiContentList({ user_text: row.label }).then((res) => {
          res.rows.forEach(async (item) => {
            this.msgList.push({ role: 'user', content: row.label });
            this.botTyping(item.content);
            this.getScaleData(item.scaleId);
          });
        });
      }
    },
    getScaleData(scaleId) {
      api.scalesList({ scaleId }).then((res) => {
        const msgItem = this.msgList[this.msgList.length - 1];
        msgItem.scaleItem = res.rows[0];
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/mixin.scss';

.app-container {
  background-image: linear-gradient(180deg, #f5fcff 0%, #d9f4ff 100%);
}

.content {
  width: 100%;
  height: calc(100% - 50px);
  // margin: 0 15px;
  display: flex;
  flex-direction: column;
  background-image: url('~@/assets/images/mindStation/customerServiceBG.png');
  background-repeat: no-repeat;
  background-position-x: calc(100% - 15px);
}

.introduction-box {
  flex-shrink: 0;
  padding: 20px 15px;

  .text {
    font-weight: bold;
    margin-bottom: 10px;
  }

  .tip {
    font-size: 14px;
    color: #8a8a8a;
  }
}

.chat-box {
  flex: 1;
  height: 0;
  padding: 15px;
  padding-top: 25px;
  border: 1px solid #fff;
  border-top-right-radius: 60px;
  background: #ffffff99;
  display: flex;
  flex-direction: column;

  .msg-content {
    flex: 1;
    overflow: auto;
    .msg-row {
      // width: 100%;
      margin: 25px 0;
      padding: 0px 10px;
      display: flex;
      justify-content: start;
      font-size: 14px;

      &.right {
        justify-content: end;
        flex-direction: row-reverse;
      }

      .user-info {
        display: flex;
        align-items: start;

        .avatar {
          width: 32px;
          height: 32px;
          margin: 0 5px;
        }
      }

      .row-content {
        max-width: 90%;
        // padding: 8px;
        // border-radius: 10px;
        // background-color: #f6f6f6;
        // white-space: pre-line;

        .content-box {
          padding: 8px;
          border-radius: 10px;
          background-color: #f6f6f6;
          white-space: pre-line;
        }

        ::v-deep p {
          margin: 0;
        }

        &.user {
          .content-box {
            background-color: #dff7ff;
          }
        }
        .follow-up-questions-list {
          display: flex;
          flex-direction: column;
          align-items: start;
          .follow-up-questions-item {
            padding: 5px;
            border-radius: 10px;
            background-color: #d2e9ff;
            margin-top: 5px;
          }
        }
      }
    }

    .list-item-box {
      background: #fff;
      border: 1px solid #f8f8f8;
      margin-top: 10px;

      .list-item {
        width: calc(100% - 20px);
        padding: 10px;
        .tag {
          margin-right: 5px;
          background: linear-gradient(151deg, #ff0000 0%, #ffafd8 80%);
          -webkit-background-clip: text;
          color: transparent;
          font-weight: bold;
        }
      }
    }

    .list-item {
      width: 100%;
      margin-top: 20px;
      display: flex;
      cursor: pointer;

      &:first-child {
        margin-top: 0px;
      }

      .item-cover {
        width: 25%;
        margin-right: 15px;
        position: relative;

        .cover-img {
          width: 100%;
        }

        .svg-icon {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          font-size: 32px;
          color: #eee;
        }

        .cover-tip {
          position: absolute;
          padding: 2px 0;
          width: 100%;
          bottom: 0;
          font-size: 14px;
          color: #fff;
          text-align: center;
          background-color: #165dff;
          opacity: 0.9;
        }
      }

      .item-label {
        font-size: 14px;
      }

      .item-label-box {
        flex: 1;
        padding: 5px 0;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .item-label {
          font-size: 15px;
        }

        .item-tip {
          font-size: 14px;
          color: #8b8b8b;
          display: -webkit-box; /* 设置为WebKit内核的弹性盒子模型 */
          -webkit-box-orient: vertical; /* 垂直排列 */
          -webkit-line-clamp: 2; /* 限制显示两行 */
          overflow: hidden; /* 隐藏超出范围的内容 */
          text-overflow: ellipsis; /* 使用省略号 */
        }
      }
    }

    .handel-box {
      display: flex;

      .handle-btn {
        flex: 1;
        margin: 10px 0;
        text-align: center;
        font-size: 15px;
        cursor: pointer;
        border-left: 1px solid #d8d8d8;

        &:first-child {
          border-left: none;
        }

        &.disable {
          color: #a8abb2;
          pointer-events: none;
          cursor: default;
        }
      }
    }
  }

  .question-box {
    flex-shrink: 0;
    width: 100%;
    padding-top: 10px;
    display: flex;
    flex-direction: column;
    align-items: start;
    // padding-top: 0px;
    // background-color: #f5f5f5;
    .asking-box {
      border-radius: 24px 6px 6px 6px;
      background: #fff;
      padding: 12px;
      margin-bottom: 10px;
      .title {
        background: linear-gradient(101deg, #ff9393 2%, #7ad1ff 98%);
        -webkit-background-clip: text;
        color: transparent;
        font-weight: bold;
        .text {
          margin-right: 10px;
        }
      }
      .list-box {
        margin-top: 10px;
        .list-row {
          font-size: 15px;
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
          &:last-child {
            margin-bottom: 0px;
          }
          .label {
            margin-right: 20px;
          }
        }
      }
    }

    .input-box {
      width: 100%;
      display: flex;
      align-items: center;

      ::v-deep .el-input {
        .el-input__inner {
          height: 40px;
          line-height: 40px;
          padding-right: 40px;
        }

        .el-input__suffix {
          right: 10px;
          display: flex;
          align-items: center;

          .svg-icon,
          .el-icon-loading {
            font-size: 22px;
            color: #0256ff;
            cursor: pointer;
          }

          .el-icon-loading {
            cursor: not-allowed;
          }
        }
      }
    }
  }
}
</style>
